package com.mibao.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

import com.mipai.R;

public class CameraActivity extends Activity {
	private Camera mCamera;
	private CameraPreview mPreview;
	private boolean islight = false;

	
	String lastPicPath = "";         // 上一张拍摄图片的文件路径
	// ///////////////////////////////////////定义mpicture
	private PictureCallback mPicture = new PictureCallback() {
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
			if (pictureFile == null) {
				Log.d(TAG, "Error creating media file, check storage permissions: ");
				return;
			}
			try {
				FileOutputStream fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
				mPreview.startPreview();
				// 更新上一张图片路径，更新ImgBtnOpenPic缩略图
				lastPicPath = pictureFile.getAbsolutePath();
				updateOpenPicImgBtn(lastPicPath);
			} catch (FileNotFoundException e) {
				Log.d(TAG, "File not found: " + e.getMessage());
			} catch (IOException e) {
				Log.d(TAG, "Error accessing file: " + e.getMessage());
			}
		}
	};

	// ///////////////////////////////////////////////////////////////////////
	// 设置聚焦
	// ////////////////////////////////////////////////////////////////////////
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Window window = getWindow();                         // 得到窗口
		window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 设置全屏
		setContentView(R.layout.camera_layout);

		// /////
		// 检查设备是否支持摄像头////////////////////////////////////////////////////////
		if (checkCameraHardware(this) == false) {
			Toast.makeText(this, "该设备不支持摄像头功能", Toast.LENGTH_LONG).show();
			return;
		}

		mCamera = getCameraInstance();

		// ///////设置摄像头参数////////////////////////////////////////////////////

		setCameraParams(mCamera);

		// 创建Preview view并将其设为activity中的内容
		mPreview = new CameraPreview(this, mCamera);
		FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
		// mPreview = (CameraPreview) findViewById(R.id.camera_preview);
		preview.addView(mPreview);
		// holder = mPreview.getHolder();//获得句柄

		// 拍照按钮的时间响应
		Button captureButton = (Button) findViewById(R.id.button_capture);
		Button flightButton = (Button) findViewById(R.id.button_test);
		// Button sationButton = (Button) findViewById(id.button_camera);

		captureButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				takeFocusedPicture();
			}
		});

		// //////////////////////闪光灯监听
		flightButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mCamera.stopPreview();
				setFlashlight(mCamera, islight);
				// ////////////////////
				if (islight) {
					((Button) v).setBackgroundResource(R.drawable.flash_auto);
				} else {
					((Button) v).setBackgroundResource(R.drawable.flash_off);
				}
				// //////////////////

				islight = !islight;
				mCamera.startPreview();

			}
		});


		// 读取保存目录中的文件，获取上一次最后拍的照片
		lastPicPath = getLastCaptureFile();
		if (lastPicPath != "")
			updateOpenPicImgBtn(lastPicPath);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mCamera == null) {
			mCamera = getCameraInstance();
			setCameraParams(mCamera);
			mPreview.setCamera(mCamera);

			mCamera.startPreview();
		}

	}

	// /////////////////////////////////////////////////////////////////
	// 释放camera/////////////////////////////////////////////////////////
	@Override
	protected void onPause() {
		super.onPause();
		releaseCamera();
	}

	// 先对焦后拍照
	public void takeFocusedPicture() {
		mCamera.autoFocus(new Camera.AutoFocusCallback() {
			@Override
			public void onAutoFocus(boolean success, Camera camera) {
				if (success && camera != null) {

					mCamera.takePicture(null, null, mPicture);
				}
			}
		});
	}

	// 读取保存目录中最新的图像文件
	String getLastCaptureFile() {
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "SuperCamera");
		if (mediaStorageDir.exists() == false) {
			return "";
		}
		File[] fs = mediaStorageDir.listFiles();
		if (fs.length <= 0)
			return "";
		Arrays.sort(fs, new CameraActivity.CompratorByLastModified());
		return fs[fs.length - 1].getPath();
	}

	// 排序器，按修改时间从新到旧排序
	static class CompratorByLastModified implements Comparator<File> {
		public int compare(File f1, File f2) {
			long diff = f1.lastModified() - f2.lastModified();
			if (diff > 0)
				return 1;
			else if (diff == 0)
				return 0;
			else
				return -1;
		}

		public boolean equals(Object obj) {
			return true;
		}
	}

	// 设置摄像头参数
	protected void setCameraParams(Camera camera) {
		camera.setDisplayOrientation(90);
		Camera.Parameters params = camera.getParameters();
		// //设置拍照时闪光灯打开
		// params.setFlashMode(Parameters.FLASH_MODE_ON);
		// ///////////////////////////////////////////////////////////////////
		// 设置聚聚焦

		params.setRotation(90);
		camera.setParameters(params);
	}

	// /////
	// 设置闪光灯函数///////////////////////////
	private void setFlashlight(Camera camera, boolean islight) {

		Camera.Parameters params = camera.getParameters();
		if (!islight) {
			params.setFlashMode(Parameters.FLASH_MODE_ON);
		} else {
			params.setFlashMode(Parameters.FLASH_MODE_OFF);
		}
		camera.setParameters(params);
	}

	// /////

	// 检查设备是否提供摄像头
	private boolean checkCameraHardware(Context context) {
		if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			// 摄像头存在
			return true;
		} else {
			// 摄像头不存在
			return false;
		}
	}

	public static Camera getCameraInstance() {
		Camera c = null;

		try {
			c = Camera.open(); // 试图获取Camera实例
		} catch (Exception e) {
			// 摄像头不可用（正被占用或不存在）
		}
		return c; // 不可用则返回null
	}

	// ///////////////////////////////////////////////////////////////////
	public class OpenPictureListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			File file = new File(lastPicPath);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(file), "image/*");
			startActivity(intent);
		}
	};

	// 更新打开图像按钮的缩略图
	public void updateOpenPicImgBtn(String path) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;                     // 表明只获取图像大小
		Bitmap bm = BitmapFactory.decodeFile(path, options);    // 由于inJustDecodeBounds为true，此时bm为null
		options.inSampleSize = options.outWidth / 64;
		options.inJustDecodeBounds = false;
		bm = BitmapFactory.decodeFile(path, options);
		ImageButton openPicBtn = (ImageButton) findViewById(R.id.imgBtnOpenPic);
		openPicBtn.setImageBitmap(bm);
	}

	// 基本的摄像头预览类
	public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

		private SurfaceHolder mHolder;
		private Camera mCamera;

		public CameraPreview(Context context, Camera camera) {
			super(context);
			mCamera = camera;
			// 安装一个SurfaceHolder.Callback，
			// 这样创建和销毁底层surface时能够获得通知。
			mHolder = getHolder();
			mHolder.addCallback(this);
			// 已过期的设置，但版本低于3.0的Android还需要
			// mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}

		public void startPreview() {
			mCamera.startPreview();
		}

		public void surfaceCreated(SurfaceHolder holder) {
			// surface已被创建，现在把预览画面的位置通知摄像头
			try {
				mCamera.setPreviewDisplay(holder);
				mCamera.startPreview();
			} catch (IOException e) {
				Log.d(TAG, "Error setting camera preview: " + e.getMessage());
			}
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			// 空代码。注意在activity中释放摄像头预览对象
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
			// 如果预览无法更改或旋转，注意此处的事件
			// 确保在缩放或重排时停止预览
			if (mHolder.getSurface() == null) {
				// 预览surface不存在
				return;
			}
			// 更改时停止预览
			try {
				mCamera.stopPreview();
			} catch (Exception e) {
				// 忽略：试图停止不存在的预览
			}
			// 在此进行缩放、旋转和重新组织格式
			// 以新的设置启动预
			try {
				mCamera.setPreviewDisplay(mHolder);
				mCamera.setDisplayOrientation(90);
				mCamera.startPreview();
			} catch (Exception e) {
				Log.d(TAG, "Error starting camera preview: " + e.getMessage());
			}
		}

		public void setCamera(Camera camera) {
			try {
				mCamera = camera;
				camera.setPreviewDisplay(mHolder);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// ///////////////////////////////////////探测SD卡是否存在
	// //////////////////////////////////////////
	// ///////////////////////////////////存储图片部分

	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	protected static final String TAG = "MainActivity";

	/** 为保存图片或视频创建文件Uri */

	private Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	// /////////////
	// 为保存图片或视频创建File
	private File getOutputMediaFile(int type) {
		// 以supercamera为目录名字在DIRECTORY_PICTURES目录下建立文件
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "SuperCamera");

		// 如果期望图片在应用程序卸载后还存在、且能被其它应用程序共享，
		// 则此保存位置最合适

		// 如果不存在的话，则创建存储目录
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				return null;
			}
		}

		File nomediapath = new File(mediaStorageDir.getPath() + "/.nomedia");
		if (!nomediapath.exists()) {
			if (!nomediapath.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				return null;
			}
		}

		// 创建媒体文件名
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
		} else {
			return null;
		}
		return mediaFile;
	}

	// /////////////////////////////////////////
	/*
	private PictureCallback mPicture = new PictureCallback() {
	    @Override 
	    public void onPictureTaken(byte[] data, Camera camera) { 
	        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); 
	        if (pictureFile == null){ 
	            Log.d(TAG, "Error creating media file, check storage permissions: "); 
	            return; 
	        }
	        try { 
	            FileOutputStream fos = new FileOutputStream(pictureFile); 
	            fos.write(data); 
	            fos.close(); 
	            mPreview.startPreview();
	            
	            // 更新上一张图片路径，更新ImgBtnOpenPic缩略图
	            
		        lastPicPath = pictureFile.getAbsolutePath();
		        updateOpenPicImgBtn(lastPicPath);
	        } catch (FileNotFoundException e) { 
	            Log.d(TAG, "File not found: " + e.getMessage()); 
	        } catch (IOException e) { 
	            Log.d(TAG, "Error accessing file: " + e.getMessage()); 
	        } 

	    } 
	};*/

	private void releaseCamera() {
		if (mCamera != null) {
			mCamera.release();        // 为其它应用释放摄像头
			mCamera = null;
		}
	}
}
